<template>
  <view class="">
    <uni-file-picker v-model="fileList"
                     :auto-upload="false"
                     :disabled="disabled"
                     :limit="limit"
                     :readonly="disabled"
                     :title="title"
                     @select="select"/>
  </view>
</template>

<script>
import { Msg } from '@/utils/BaseUtils'
import {UploadRequest} from "@/utils/request/request";

export default {
  components: {},
  props: {
    title: {type: String, default: ''},
    limit: {type: Number, default: 1},
    disabled: {type: Boolean, default: false},
    modelValue: {type: String, default: ''},
  },
  emits: ['update:modelValue', 'change'],
  data() {
    return {
      fileList: [],
      fileIds: []
    };
  },
  watch: {
    fileList(nv) {
      this.fileIds = nv.map(item => item.fileID);
    },
    modelValue: {
      immediate: true,
      handler(nv) {
        this.getPreview(nv);
      }
    }
  },
  methods: {
    // 获取上传状态
    async select(e) {
      const list = e.tempFilePaths || [];
      Msg.loading(async (close) =>{
        for (let i = 0; i < list.length; i++) {
          await UploadRequest.upload(list[i], this.fileIds.join(",")).then(info => {
            this.$emit("update:modelValue", UploadRequest.convertFileIds(this.fileIds.join(","), info.fileId))
          })
        }
        close?.();
      }, '上传中...')
    },
    async getPreview(ids) {
      if (!ids) {
        this.fileList = [];
        return;
      }
      await UploadRequest.getFileInfo(ids).then(({data: infos = []}) => {
        this.fileList = (infos || []).map(info => ({...info, url: info.path, id: info.id, fileID: info.id}))
      })
    }
  }
}
</script>

<style lang="scss">
::v-deep(.file-title) {
  font-size: 0.85em;
}
</style>
